<template>
  <div class="device-dashboard">
    <el-row :gutter="20">
      <!-- 设备概览卡片 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>设备概览</span>
              <el-button type="text" @click="refreshDeviceStats">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="dashboard-data">
            <div class="data-item">
              <div class="data-value">{{ deviceStats.total }}</div>
              <div class="data-label">总设备数</div>
            </div>
            <div class="data-item">
              <div class="data-value">{{ deviceStats.active }}</div>
              <div class="data-label">启用设备</div>
            </div>
            <div class="data-item">
              <div class="data-value">{{ deviceStats.disabled }}</div>
              <div class="data-label">禁用设备</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 收入统计卡片 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>收入统计</span>
              <el-button type="text" @click="goToIncome">
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="income-chart">
            <div class="income-summary">
              <div class="total-income">¥{{ incomeData.totalIncome }}</div>
              <div class="income-period">本月收入</div>
            </div>
            <div class="income-trend">
              <div class="trend-label">较上月</div>
              <div class="trend-value" :class="incomeData.growth >= 0 ? 'positive' : 'negative'">
                {{ incomeData.growth >= 0 ? '+' : '' }}{{ incomeData.growth }}%
                <el-icon v-if="incomeData.growth >= 0"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 待处理事项卡片 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>待处理事项</span>
              <el-button type="text" @click="viewAllPendingItems">
                <el-icon><View /></el-icon>
              </el-button>
            </div>
          </template>
          <el-empty v-if="pendingItems.length === 0" description="暂无待处理事项"></el-empty>
          <div v-else class="pending-list">
            <div v-for="(item, index) in pendingItems" :key="index" class="pending-item">
              <el-tag :type="getTagType(item.type)">{{ item.type }}</el-tag>
              <span class="item-title">{{ item.title }}</span>
              <span class="item-time">{{ item.time }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设备列表 -->
    <el-card shadow="hover" class="device-list-card">
      <template #header>
        <div class="card-header">
          <span>我的设备</span>
          <el-button type="primary" size="small" @click="goToAddDevice">添加设备</el-button>
        </div>
      </template>
      <el-table :data="devices" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="设备ID" width="80" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="deviceCode" label="设备编号" width="120" />
        <el-table-column prop="type" label="设备类型" width="120" />
        <el-table-column prop="location" label="位置" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" width="180" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="viewDeviceDetail(scope.row.id)">详情</el-button>
            <el-button type="success" size="small" link @click="editDevice(scope.row.id)">编辑</el-button>
            <el-button 
              :type="scope.row.status === 0 ? 'success' : 'warning'" 
              size="small" 
              link 
              @click="toggleDeviceStatus(scope.row)"
            >
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-button>
            <el-button type="danger" size="small" link @click="confirmDeleteDevice(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowUp, ArrowDown, Refresh, ArrowRight, View } from '@element-plus/icons-vue';

// 导入API服务
import { getDeviceStats, getDeviceList, deleteDevice, enableDevice, disableDevice } from '@/api/device';
import { getMonthlyIncome } from '@/api/income';
import { getPendingNotifications } from '@/api/notification';

const router = useRouter();
const loading = ref(false);

// 设备统计数据
const deviceStats = reactive({
  total: 0,
  active: 0,
  disabled: 0
});

// 收入数据
const incomeData = reactive({
  totalIncome: '0.00',
  growth: 0
});

// 待处理事项
const pendingItems = ref([]);

// 设备列表数据
const devices = ref([]);

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 初始化
onMounted(() => {
  fetchDeviceStats();
  fetchIncomeData();
  fetchPendingItems();
  fetchDevices();
});

// 获取设备统计数据
const fetchDeviceStats = async () => {
  try {
    const { data } = await getDeviceStats();
    console.log('设备统计数据', data);
    if (data.code === 200) {
      const statsData = data.data;
      deviceStats.total = statsData.total;
      deviceStats.active = statsData.active;
      deviceStats.disabled = statsData.disabled;
    } else {
      ElMessage.error(data.message || '获取设备统计失败');
    }
  } catch (error) {
    console.error('获取设备统计失败:', error);
    ElMessage.error('获取设备统计失败');
  }
};

// 获取收入数据
const fetchIncomeData = async () => {
  try {
    const { data } = await getMonthlyIncome();
    console.info('获取收入数据成功:', data)
    if (data.code === 200) {
      const incomeResult = data.data;
      incomeData.totalIncome = incomeResult.totalIncome.toLocaleString();
      incomeData.growth = incomeResult.growth;
    } else {
      ElMessage.error(data.message || '获取收入数据失败');
    }
  } catch (error) {
    console.error('获取收入数据失败:', error);
    ElMessage.error('获取收入数据失败');
  }
};

// 获取待处理事项
const fetchPendingItems = async () => {
  try {
    const { data } = await getPendingNotifications();
    console.log('获取待处理事项', data);
    if (data.code === 200) {
      pendingItems.value = data.data;
    } else {
      ElMessage.error(data.message || '获取待处理事项失败');
    }
  } catch (error) {
    console.error('获取待处理事项失败:', error);
    ElMessage.error('获取待处理事项失败');
  }
};

// 获取设备列表
const fetchDevices = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    };
    const { data } = await getDeviceList(params);
    console.log('设备列表响应:', data);
    if (data.code === 200) {
      devices.value = data.data.records;
      pagination.total = data.data.total;
    } else {
      ElMessage.error(data.message || '获取设备列表失败');
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
    ElMessage.error('获取设备列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新设备统计
const refreshDeviceStats = () => {
  fetchDeviceStats();
  ElMessage.success('设备统计已刷新');
};

// 跳转到收入页面
const goToIncome = () => {
  router.push('/device-owner/income');
};

// 查看所有待处理事项
const viewAllPendingItems = () => {
  router.push('/device-owner/notifications');
};

// 跳转到添加设备页面
const goToAddDevice = () => {
  router.push('/device-owner/devices/add');
};

// 查看设备详情
const viewDeviceDetail = (id) => {
  router.push(`/device-owner/devices/${id}`);
};

// 编辑设备
const editDevice = (id) => {
  router.push(`/device-owner/devices/${id}/edit`);
};

// 切换设备状态
const toggleDeviceStatus = async (device) => {
  try {
    let response;
    if (device.status === 0) {
      response = await enableDevice(device.id);
    } else {
      response = await disableDevice(device.id);
    }
    
    const { data } = response;
    if (data.code === 200) {
      ElMessage.success(device.status === 0 ? '设备已启用' : '设备已禁用');
      fetchDevices();
      fetchDeviceStats();
    } else {
      ElMessage.error(data.message || '操作失败');
    }
  } catch (error) {
    console.error('切换设备状态失败:', error);
    ElMessage.error('操作失败');
  }
};

// 确认删除设备
const confirmDeleteDevice = (id) => {
  ElMessageBox.confirm('确定要删除该设备吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    performDeleteDevice(id);
  }).catch(() => {});
};

// 执行删除设备
const performDeleteDevice = async (id) => {
  try {
    const { data } = await deleteDevice(id);
    if (data.code === 200) {
      ElMessage.success('删除设备成功');
      fetchDevices();
      fetchDeviceStats();
    } else {
      ElMessage.error(data.message || '删除设备失败');
    }
  } catch (error) {
    console.error('删除设备失败:', error);
    ElMessage.error('删除设备失败');
  }
};

// 获取标签类型
const getTagType = (type) => {
  const typeMap = {
    '协商': 'warning',
    '合同': 'primary',
    '付款': 'success',
    '警告': 'danger'
  };
  return typeMap[type] || 'info';
};

// 分页方法
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchDevices();
};

const handleCurrentChange = (page) => {
  pagination.current = page;
  fetchDevices();
};
</script>

<style scoped>
.device-dashboard {
  padding: 20px;
}

.dashboard-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dashboard-data {
  display: flex;
  justify-content: space-between;
}

.data-item {
  text-align: center;
  flex: 1;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.data-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.income-chart {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.total-income {
  font-size: 28px;
  font-weight: bold;
  color: #67C23A;
}

.income-period {
  color: #606266;
  margin-top: 5px;
}

.income-trend {
  text-align: right;
}

.trend-label {
  color: #909399;
  font-size: 12px;
}

.trend-value {
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 5px;
}

.positive {
  color: #67C23A;
}

.negative {
  color: #F56C6C;
}

.pending-list {
  max-height: 200px;
  overflow-y: auto;
}

.pending-item {
  padding: 10px 0;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #EBEEF5;
}

.pending-item:last-child {
  border-bottom: none;
}

.item-title {
  margin-left: 10px;
  flex: 1;
}

.item-time {
  color: #909399;
  font-size: 12px;
}

.device-list-card {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>